import 'package:flame/components.dart';
import 'package:flame/effects.dart';
import 'package:hero_back/study/flutter_game_flame/day002/component.dart';

class GirlComponent extends SpriteAnimationComponent with HasGameRef{
  final double speed = 100;
  late Sprite bulletSprite;

  @override
  Future<void> onLoad() async {
    List<Sprite> sprites = [];
    for (int i = 1; i <= 10; i++) {
      sprites.add(
          await Sprite.load('girl/girl0${i.toString().padLeft(2, "0")}.png'));
    }
    animation =
        SpriteAnimation.spriteList(sprites, stepTime: 0.15, loop: false);
    playing = false;

    bulletSprite = await gameRef.loadSprite('monster.png');
    animation?.onComplete = () {
      animation!.currentIndex = 0;
      animation!.update(0);

      ///添加子弹
      Bullet bullet = Bullet(sprite: bulletSprite, maxRange: 200);
      bullet.size = Vector2(32, 32);
      bullet.anchor = Anchor.center;
      bullet.priority = 1;
      priority = 2;
      bullet.position = position - Vector2(0, -3);
      gameRef.add(bullet);
    };
  }

  @override
  void onGameResize(Vector2 size) {
    super.onGameResize(size);
    position = size / 2;
  }

  GirlComponent() : super(size: Vector2(150, 150), anchor: Anchor.center);

  void toTarget(Vector2 target) {
    ///移除之前移动，防止对下次的移动产生影响
    removeAll(children.whereType<MoveEffect>());
    double timeMs = (target - position).length / speed;
    add(MoveEffect.to(target, EffectController(duration: timeMs)));
  }

  void shoot() {
    playing = true;
    animation?.reset();
  }
}
